<script>

import { isNull } from "@/utils/service";
import { getStoreOptions, downloadExcel } from "@/views/store/pdd/api/index.js";
import download from "@/plugins/download";
import TbColumn from "@/components/table/tbColumn";
import ColumnManager from "@/components/table/columnManager.vue";
import { COLUMNS } from "@/views/store/pdd/columns";

export default {
  name: "pddStore",
  components: { ColumnManager },
  computed: {},
  mounted() {
    this.getPddList();
  },
  data(){
    let _vm = this;
    return {
      searchName: "",
      storeOptions: [],
      dateScope: [],
      dates: [],
      dialogVisible: false,
      dialogSearchName: "",
      dialogDateScope: [],
      table: {
        tbLoading: false,
        /* 选中行数据 */
        sRows: [],
        data: [],
        pageNo: 1,
        pages: 0,
        pageSize: 30,
        pageCount: 0,
        sortField: "",
        sortMode: void 0,
        handleSizeChange(pageSize) {
          if (pageSize === _vm.table.pageSize) {
            return;
          }
          _vm.table.pageSize = pageSize;
          _vm.getPddList();
        },
        handleCurrentChange(pageNo) {
          if (pageNo === _vm.table.pageNo) {
            return;
          }
          _vm.table.pageNo = pageNo;
          _vm.getPddList();
        },
        sRowChange(rows) {
          _vm.table.sRows = rows;
        },
      },
      /** DatePicker 日期选择器 */
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      tbColumns: COLUMNS
    }
  },
  methods: {
    isNull,
    refreshColumns(columns) {
      this.tbColumns = TbColumn.buildArray(columns);
      console.log(this.tbColumns);
      this.$nextTick(() => {
        this.$refs.myTb.doLayout();
      });
    },
    tableDataProvider(){
      return JSON.parse(JSON.stringify(this.table.data))
    },
    toRender(componentData) {
      this.table.data = componentData.tableList;
    },
    getStoreOptions() {
      getStoreOptions(this, res => {
        this.storeOptions = res;
      })
    },
    getPddList() {
      let _t = this;

      _t.table.tbLoading = true;

      this.$request.post({
        url: 'store/pdd/page',
        params: {
          pageNo: _t.table.pageNo,
          pageSize: _t.table.pageSize,
          storeName: _t.searchName,
          dates: _t.dates,
          sortField: _t.table.sortField,
          sortMode: _t.table.sortMode
        },
        success: res => {
          _t.table.data = res.list
          _t.table.pageCount = res.total
          _t.table.pageSize = res.pageSize
          _t.table.pageNo = res.pageNo
          _t.table.pages = res.pages
        },
        error: (res) => {
          console.log(res);
        },
        finally: () => {
          _t.table.tbLoading = false;
        }
      });
    },
    download() {
      if(isNull(this.dialogSearchName) || isNull(this.dialogDateScope)) {
        this.$message.warning('请选择店铺名称与数据周期')
        return
      }
      const [startDate, endDate] = this.dialogDateScope;
      const startDateStr = startDate.substring(5, 7) + startDate.substring(8, 10);
      const endDateStr = endDate.substring(5, 7) + endDate.substring(8, 10);
      const fileName = this.dialogSearchName + startDateStr + '-' + endDateStr;
      /** 下载 Excel */
      downloadExcel(this, this.dialogSearchName, startDate, endDate, res => {
        download.excel(res.data, fileName)
        this.$message.success('下载成功')
      })
      this.dialogVisible = false; // 下载后关闭 dialog
    },
    /* 清空分页条件 */
    clearPageConditions(){
      this.searchName = ""
      this.dates = []
      this.getPddList()
    },
    tableSortChange(column, prop, order){
      if (!isNull(column.order)) {
        this.table.sortField = column.prop;
        if (column.order.startsWith("asc")) {
          this.table.sortMode = "ASC";
        } else {
          this.table.sortMode = "DESC";
        }
      } else {
        this.table.sortMode = "ASC";
      }
      this.getPddList()
    }
  }
}
</script>

<template>
  <div style="margin: 10px 0">
    <div class="header">
      <el-select
        @focus="getStoreOptions"
        style="width: 230px"
        size="mini"
        v-model="searchName" clearable filterable placeholder="请选择店铺">
        <el-option
          v-for="item in storeOptions"
          :key="item"
          :label="item"
          :value="item">
        </el-option>
      </el-select>

      <el-date-picker
        style="width: 230px; height: 39px; margin-left: 5px"
        size="mini"
        type="dates"
        v-model="dates"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="选择一个或多个日期">
      </el-date-picker>

      <el-button style="margin-left: 5px" size="mini" type="primary" icon="el-icon-search" @click="getPddList">搜索</el-button>
      <el-button style="margin-left: 5px" size="mini" type="info"  icon="el-icon-refresh" @click="clearPageConditions">清空</el-button>

      <el-tooltip style="margin-left: 5px" effect="dark" content="导出 Excel 表格文件" placement="right">
        <el-button size="mini" type="success" icon="el-icon-download" @click="dialogVisible = true">导出</el-button>
      </el-tooltip>

      <el-dialog
        title="导出 Excel 表格文件"
        :visible.sync="dialogVisible"
        width="30%">
        <el-select
          @focus="getStoreOptions"
          style="width: 230px"
          v-model="dialogSearchName" clearable filterable placeholder="请选择店铺">
          <el-option
            v-for="item in storeOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-date-picker
          class="dateClass"
          style="width: 230px; height: 39px; margin-left: 5px"
          v-model="dialogDateScope"
          type="daterange"
          align="center"
          unlink-panels
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="download(); dialogVisible = false">下 载</el-button>
        </span>
      </el-dialog>

      <div>
        <column-manager style="margin-left: 5px" :columns="tbColumns" @refreshColumns="refreshColumns" />
      </div>

    </div>
    <div class="main">
      <el-table
        ref="myTb"
        @selection-change="table.sRowChange"
        v-loading="table.tbLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%"
        height="73vh"
        :row-style="{height:'20px'}"
        :cell-style="{padding:'0px'}"
        border
        :data="table.data"
        @sort-change="tableSortChange"
      >
        <el-table-column
          v-for="(item, index) in tbColumns.filter(item => item.enabled && item.show)"
          :label="item.label"
          :prop="item.prop"
          :align="item.align"
          :width="item.width"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :sortable="item.sortable"
          :formatter="item.formatter"
        >
          <template v-if="item.prop === 'conversionRate'" #default="{row, column, $index}">
            {{ !isNull(row.conversionRate) ? row.conversionRate + '%' : '-' }}
          </template>
          <template v-else-if="item.prop === 'comprehensiveScoreIndustryRanking'" #default="{row, column, $index}">
            {{ !isNull(row.comprehensiveScoreIndustryRanking) ? row.comprehensiveScoreIndustryRanking + '%' : '-' }}
          </template>
          <template v-else-if="item.prop === 'helpRate'" #default="{row, column, $index}">
            {{ !isNull(row.helpRate) ? row.helpRate + '%' : '-' }}
          </template>

        </el-table-column>

      </el-table>
    </div>

    <div class="footer">
      <div>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change=table.handleSizeChange
          @current-change=table.handleCurrentChange
          :total=table.pageCount
          :page-sizes="[30, 50, 100, 300]"
          :page-size=table.pageSize
          :page-count=table.pages
          :current-page=table.pageNo
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<style scoped>
.header {
  margin: 10px 0 10px 0
}

.main {
  margin: 10px 0 10px 0
}

.footer {
  display: flex;
  justify-content: space-between;
}
</style>